package com.qi.config;

/**
 * @author zjq
 * @version 1.0
 * @date 2021/12/2 20:54
 */

import com.qi.pojo.Configuration;
import com.qi.pojo.Mapper;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.List;

/**
 * 获取XML文件
 */
//@Slf4j
public class XmlMapperBuilder {
    private Configuration configuration = null;

    public XmlMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public Configuration loadMapper(File file) throws DocumentException, ClassNotFoundException {
//        Document document = new SAXReader().read(input);
        Document document = new SAXReader().read(file);
        Element rootElement = document.getRootElement();
        String namespace = rootElement.attributeValue("namespace");

        List<Node> selectNodes = rootElement.selectNodes("//select");
        for (int i = 0; i < selectNodes.size(); i++) {
            Mapper mapper = new Mapper();
            Element element = (Element) selectNodes.get(i);
            String id = element.attributeValue("id");
            mapper.setId(id);
            String paramType = element.attributeValue("paramType");
            if (paramType != null && !paramType.isEmpty()) {
                mapper.setParamType(Class.forName(paramType));
            }
            String resultType = element.attributeValue("resultType");
            if (resultType != null && !resultType.isEmpty()) {
                mapper.setResultType(Class.forName(resultType));
            }
            mapper.setSql(element.getTextTrim());
            String key = namespace + "." + id;
            configuration.getMapperMap().put(key, mapper);
        }
        return configuration;
    }
}
